import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'


Vue.use(VueRouter)


// 原型上修改push方法
const originPush = VueRouter.prototype.push  // 先将之前的存储到一个变量当中
const originReplace = VueRouter.prototype.replace // 同上

VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originPush.call(this, location, onResolve, onReject)
    return originPush.call(this, location).catch(err => err)
}

VueRouter.prototype.replace = function replace(location, onResolve, onReject) {
    if (onResolve || onReject) return originReplace.call(this, location, onResolve, onReject)
    return originReplace.call(this, location).catch(err => err)
}


const router = new VueRouter({
    mode: 'history',
    routes,
    scrollBehavior(to, from, savedPosition) {
        // console.log(to,from);
        // to 表示要跳转到的页面 是一个路由规则对象 
        // from 表示从哪里跳转过来 也是一个路由规则对象
        // savedPosition 记录之前的页面位置  当浏览器的前进或后退按钮被单击的时候会触发
        // // console.log(savedPosition);
        if (savedPosition) {
            return savedPosition
        } else {
            return { x: 0, y: 0 }
        }
    }
})

router.beforeEach(async (to, from, next) => {
    // console.log(store);
    let token = store.state.user.token
    let userInfo = store.state.user.userInfo

    // 如果有token
    if (token) {
        //如果用用还在点登录页面
        if (to.path === '/login') {
            next('/')
        } else {
            //用户没有在登录页且用户信息存在
            if (userInfo.name) {
                next()
            } else {
                //用户没有在登录页且用户信息不存在
                try {
                    //获取用户信息
                    await store.dispatch('user/getTokenUserInfo')
                    next()
                } catch (error) {

                    next('/login')
                }
            }
        }
    } else {
        //代表没有登录过
        // 交易相关、支付相关、用户中心相关
        let target = to.path
        // console.log('打印', target);
        if (target.indexOf('/trade') === 0 || target.indexOf('/pay') === 0 || target.startsWith('/center')) {
            next('/login?redirect=' + target)
        } else {
            next()
        }

    }
})

export default router